<template>
  <el-menu
    :default-active="$route.path"
    class="el-menu-vertical-demo"
    router
    background-color="#fff"
    text-color="#333"
    active-text-color="#409EFF"
  >
    <template v-for="menu in menuList">
      <!-- 没有子菜单的情况 -->
      <el-menu-item v-if="!hasChildren(menu)" :key="menu.id" :index="menu.url">
        <i :class="getIcon(menu.name)"></i>
        <span slot="title">{{ menu.name }}</span>
      </el-menu-item>
      
      <!-- 有子菜单的情况 -->
      <el-submenu v-else :key="menu.id" :index="menu.url">
        <template slot="title">
          <i :class="getIcon(menu.name)"></i>
          <span>{{ menu.name }}</span>
        </template>
        <el-menu-item 
          v-for="child in getChildren(menu.id)"
          :key="child.id"
          :index="getFullUrl(menu.url, child.url)"
        >
          {{ child.name }}
        </el-menu-item>
      </el-submenu>
    </template>
  </el-menu>
</template>

<script>
import { getAdminPermission } from '@/api/contract'

export default {
  name: 'Sidebar',
  data() {
    return {
      menuData: [] // 存储菜单数据
    }
  },
  computed: {
    // 获取顶级菜单（parentId 为 0 的菜单）
    menuList() {
      return this.menuData
        .filter(menu => menu.parentId === 0)
        .sort((a, b) => a.listorder - b.listorder)
    }
  },
  methods: {
    // 判断是否有子菜单
    hasChildren(menu) {
      return this.menuData.some(item => item.parentId === menu.id)
    },
    // 获取子菜单
    getChildren(parentId) {
      return this.menuData
        .filter(menu => menu.parentId === parentId)
        .sort((a, b) => a.listorder - b.listorder)
    },
    // 获取完整的URL（父菜单URL + 子菜单URL）
    getFullUrl(parentUrl, childUrl) {
      // 移除开头的斜杠，避免重复
      const cleanParentUrl = parentUrl.replace(/^\//, '')
      const cleanChildUrl = childUrl.replace(/^\//, '')
      return `/${cleanParentUrl}/${cleanChildUrl}`
    },
    // 根据菜单名称获取对应的图标
    getIcon(name) {
      const iconMap = {
        '首页': 'el-icon-s-home',
        '权限管理': 'el-icon-setting',
        '菜单管理': 'el-icon-menu',
        '卡密管理': 'el-icon-menu',
        '淘宝链接': 'el-icon-menu'
      }
      return iconMap[name] || 'el-icon-menu'
    },
    // 获取菜单数据
    async fetchMenuData() {
      if (this.$route.path === '/login') {
        return;
      }
      try {
        const response = await getAdminPermission()
        if (response.data.code === 200) {
          this.menuData = response.data.data
          // 如果当前在根路径，则跳转到第一个菜单
          if (this.$route.path === '/') {
            this.navigateToFirstMenu()
          }
        }
      } catch (error) {
        console.error('获取菜单数据失败:', error)
      }
    },
    // 导航到第一个菜单
    navigateToFirstMenu() {
      if (this.menuList.length > 0) {
        const firstMenu = this.menuList[0]
        if (this.hasChildren(firstMenu)) {
          // 如果有子菜单，跳转到第一个子菜单
          const children = this.getChildren(firstMenu.id)
          if (children.length > 0) {
            this.$router.push(this.getFullUrl(firstMenu.url, children[0].url))
          }
        } else {
          // 如果没有子菜单，直接跳转
          this.$router.push(firstMenu.url)
        }
      }
    }
  },
  created() {
    // 组件创建时获取菜单数据
    this.fetchMenuData()
  },
  // 监听路由变化，重新获取菜单数据
  watch: {
    '$route': {
      handler() {
        this.fetchMenuData()
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.el-menu-vertical-demo {
  height: 100%;
  border-right: none;
  background-color: white !important;
  border-top:2px;
  border-color: #409EFF !important;
}

/* 覆盖 Element UI 的默认样式 */
.el-menu {
  background-color: white !important;
}

.el-menu-item {
  background-color: white !important;
}

.el-menu-item:hover {
  background-color: #f5f7fa !important;
}

.el-submenu__title {
  background-color: white !important;
}

.el-submenu__title:hover {
  background-color: #f5f7fa !important;
}

.el-menu-item.is-active {
  background-color: white !important;
  color: #409EFF !important;
}
</style> 